package com.example.crossborderecommerce.controller;

import com.example.crossborderecommerce.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上下载模块
 */

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${File.basePath}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        //拿到源文件的名字
        String originalFilename = file.getOriginalFilename();
        //拿到文件的后缀名如.jpg
        String type = originalFilename.substring(originalFilename.lastIndexOf('.'));

        //使用UUID重新生成文件名，防止同名文件覆盖
        String fileName = UUID.randomUUID().toString() + type;
        String filePath = basePath + fileName;
        //查看basePath的文件目录是否存在，不存在则创建
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdir();
        }

        try {
            //将临时文件转储到固定位置使之持久化
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success("文件上传成功", fileName);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;

        response.setContentType("image/jpeg");

        try {
            //输入流读取文件内容
            fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流写回浏览器
            outputStream = response.getOutputStream();

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
